package template.security;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 使用Hibernate的HQL来获取登录用户信息。
 * 要注入通过账号查询用户和用户所有的权限的HQL语句。
 * 返回的UserDetails包括了从数据库中获得的完整的信息。
 * 
 * @author mengyang
 *
 */
public class HibernateUserDetailsServiceImpl extends HibernateDaoSupport implements
		UserDetailsService {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	// 用于查询用户信息的HQL语句
	private String usersByUsernameQuery;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		List<UserDetails> userDetailsList = getHibernateTemplate().find(usersByUsernameQuery, username);

		if(userDetailsList != null && userDetailsList.size() > 0){
			return userDetailsList.get(0);
		} else {
			throw new UsernameNotFoundException("没找到账号：'" + username + "'对应的用户信息。");
		}
		
	}

	public String getUsersByUsernameQuery() {
		return usersByUsernameQuery;
	}

	public void setUsersByUsernameQuery(String usersByUsernameQuery) {
		this.usersByUsernameQuery = usersByUsernameQuery;
	}

}
